package com.fourinone.utils;

import org.xml.sax.InputSource;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;

/**
 * @Description
 * @auther Szper
 * @create 2019-10-15 10:37
 */
public class XmlUtil {
    public ArrayList getXmlObjectByFile(String filePath, String PROP_DESC, String KEY_DESC) {
        ArrayList al = new ArrayList();
        try {
            XmlParse handler = new XmlParse();
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();
            InputSource src = new InputSource(new FileInputStream(filePath));
            if(PROP_DESC != null) {
                handler.setPROP_DESC(PROP_DESC);
            }
            if (KEY_DESC != null) {
                handler.setKEY_DESC(KEY_DESC);
            }
            saxParser.parse(src, handler);
            al = handler.getPropsAl();
        } catch (FileNotFoundException e) {
            System.err.println("|XmlSetting||Can't find setting file:" + filePath + ", and create setting.xml in the path.|");
            // 文件适配器占位
        } catch (Throwable t) {
            System.err.println("|XmlSetting||Wrong: get XmlInfo from file|");

        }
        return al;
    }
    /**
     * 默认配置文件 设置MASTER和SLAVER的
     * @return
     */
    private String getDefaultConfig() {
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        sb.append("<PROPS DESC=\"TABLENAME\">\n");
            sb.append("\t<PROP DESC=\"MASTER\">\n");
                sb.append("\t\t<SERVERS>localhost:1888,localhost:1889</SERVERS>\n");
                sb.append("\t\t<SAFEMEMORYPER>0.95</SAFEMEMORYPER>\n");
                sb.append("\t\t<HEARTBEAT>3000</HEARTBEAT>\n"); //心跳
                sb.append("\t\t<MAXDELAY>30000</MAXDELAY>\n");
                sb.append("\t\t<EXPIRATION>24</EXPIRATION>\n");
                sb.append("\t\t<CLEARPERIOD>0</CLEARPERIOD>\n");
                sb.append("\t\t<ALWAYSTRYLEADER>false</ALWAYSTRYLEADER>\n");//leader
                sb.append("\t\t<STARTWEBAPP>true</STARTWEBAPP>\n");
            sb.append("\t</PROP>\n");
            sb.append("\t<PROP DESC=\"SLAVER\">\n");
                sb.append("\t\t<TIMEOUT DESC=\"FALSE\">2</TIMEOUT>\n");
                sb.append("\t\t<SERVERS>localhost:2088</SERVERS>\n");
                sb.append("\t\t<SERVICE>false</SERVICE>\n");
             sb.append("\t</PROP>\n");
            sb.append("</PROPS>");
        return sb.toString();
    }
}
